package com.uduemc.biso.node.web.api.validator.currentsite.impl;

import java.io.IOException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.component.SpringContextUtils;
import com.uduemc.biso.node.web.api.service.CategoryService;
import com.uduemc.biso.node.web.api.validator.currentsite.CurrentSiteSCategoryIdExist;

public class CurrentSiteSCategoryIdExistValid implements ConstraintValidator<CurrentSiteSCategoryIdExist, Long> {
	private static final Logger logger = LoggerFactory.getLogger(CurrentSiteSCategoryIdExistValid.class);

	@Override
	public void initialize(CurrentSiteSCategoryIdExist constraintAnnotation) {

	}

	@Override
	public boolean isValid(Long value, ConstraintValidatorContext context) {
		if (value == null) {
			return true;
		}
		if (value.longValue() < 1) {
			return true;
		}
		CategoryService categoryServiceImpl = SpringContextUtils.getBean("categoryServiceImpl", CategoryService.class);
		RequestHolder requestHolder = SpringContextUtils.getBean("requestHolder", RequestHolder.class);
		SCategories sCategories = null;
		try {
			sCategories = categoryServiceImpl.findOne(value);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (sCategories == null) {
			logger.error("未能查询到 SCategories 数据：" + value);
			return false;
		}
		if (sCategories.getHostId().longValue() != requestHolder.getHost().getId().longValue()) {
			logger.error("查询到 SCategories 的数据hostId不匹配。 requestHolder.getHost().getId().longValue(): "
					+ requestHolder.getHost().getId().longValue() + " sCategories.getHostId().longValue(): "
					+ sCategories.getHostId().longValue() + " value: " + value);
			return false;
		}
		if (sCategories.getSiteId().longValue() != requestHolder.getCurrentSite().getId().longValue()) {
			logger.error("查询到 SCategories 的数据siteId不匹配。requestHolder.getCurrentSite().getId().longValue(): "
					+ requestHolder.getCurrentSite().getId().longValue() + " sCategories.getSiteId().longValue(): "
					+ sCategories.getSiteId().longValue() + " value: " + value);
			return false;
		}
		return true;
	}

}
